import createUserTempId from "@/utils/createUserTempId";

import { requestLogin, requestUserInfo, requestLogout } from "@/api/Login";

const state = {
  userTempId: createUserTempId(),
  token: localStorage.getItem("USER_TOKEN") || null,
  userInfo: null,
};

const mutations = {
  SET_TOKEN_STATE(state, value) {
    state.token = value;
  },
  SET_USERINFO_STATE(state, value) {
    state.userInfo = value;
  },
  SET_LOGOUT_STATE(state) {
    state.token = "";
    localStorage.removeItem("USER_TOKEN");
    state.userInfo = null;
  },
};

const actions = {
  async loginAction({ commit }, value) {
    const { token } = await requestLogin(value);
    commit("SET_TOKEN_STATE", token);
    // 将 token 存储在本地
    localStorage.setItem("USER_TOKEN", token);
  },
  async userInfoAction({ commit }) {
    commit("SET_USERINFO_STATE", await requestUserInfo());
  },
  async logoutAction({ commit }) {
    await requestLogout();
    commit("SET_LOGOUT_STATE");
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
